// pages/device/index.js
const storageService = require('../../services/storage')
import * as echarts from '../ec-canvas/echarts';
import {
  Base64
} from '../../utils/base64';
import * as comm from '../../utils/common';

var option = {
  legend: {
    itemWidth: 8,
    itemHeigh: 5,
    data: [],
    top: 10,
    left: 'center',
    z: 100
  },
  grid: {
    right: '20rpx', // 右边距
    bottom: '20rpx',
    top: '30rpx'
  },
  tooltip: {
    //trigger: 'axis',
    //showContent: false
  },
  xAxis: {
    type: 'value',
    interval: 100,
    min: 800,
    max: 2000,
    axisLabel: {
      color: "#FFF",
      formatter: function (value) {
        return value / 100;
      }
    },
    splitLine: {
      show: false
    } // 去除x轴的分割线
  },
  yAxis: {
    x: 'center',
    type: 'value',
    min: 0,
    max: 100,
    interval: 20, // 指定刻度间隔
    axisLabel: {
      color: "#FFF"
    },
    splitLine: {
      lineStyle: {
        type: 'dashed'
      }
    }
  },
  series: []
};
// 获取 App 实例
const appInstance = getApp();
Component({
  options: {
    multipleSlots: true // 在组件定义时的选项中启用多slot支持
  },
  /**
   * 组件的属性列表
   */
  properties: {
    did: {
      type: String,
      value: ''
    },
  },
  data: {
    ecW: 0,
    ec: {
      lazyLoad: true
    },
    isLoaded: false,
    isDisposed: false,
    popW: 0,
    popH: 0,

    autoCfg: {},
    deviceCfg: {},
    channels: [],

    minutePickerVisible: false,
    minutePickerVal: "00:00",

    longtap: false,
    showWithInput: false,
    modeName: "",

    showChEdit: false,

    popVisible: false,
    popTimes: [],
    popDelTime: "",
    popDelConfirmVisible: false,
    popImportConfirmVisible: false,
    popSyncToDeviceConfirmVisible: false,
    popSyncFromDeviceConfirmVisible: false,
  },
  lifetimes: {
    attached() {
      console.log("attached....................free");
      const $t = this;
      $t.setData({
        ecW: appInstance.globalData.windowWidth / 2,
        popW: appInstance.globalData.windowWidth * 0.8,
        popH: appInstance.globalData.windowHeight * 0.5
      });

      let dobj = storageService.getDeviceInfo(this.data.did)
      this.data.deviceCfg = dobj;
      this.getAndInitChs();


      // 获取组件
      this.ecComponent = this.selectComponent('.mychart-dom-bar');
      this.initEchartOption();
      this.init();

    },
  },
  /**
   * 组件的方法列表
   */
  methods: {
    getAndInitChs(autoCfg) {
      if (autoCfg == null || autoCfg == undefined) {
        autoCfg = storageService.getAutoCfg(this.data.did)
      }
      if (comm.isEmptyObj(autoCfg)) {
        let chCfg = storageService.getDeviceChannels(this.data.did)
        autoCfg = {
          sel: 0,
          modes: [{
              "nm": "LPS",
              "cls": []
            },
            {
              "nm": "SPS",
              "cls": []
            },
            {
              "nm": "LPS+SPS",
              "cls": []
            },
            {
              "nm": "模式一",
              "cls": []
            },
            {
              "nm": "模式二",
              "cls": []
            },
            {
              "nm": "模式三",
              "cls": []
            }
          ]
        };
        for (var j = 0; j < autoCfg.modes.length; j++) {
          let cls = autoCfg.modes[j].cls;
          for (var i = 0; i < chCfg.length; i++) {
            if (chCfg[i].u == 0) {
              continue;
            }
            cls.push({
              "n": chCfg[i].n,
              "nm": chCfg[i].nm,
              "c": chCfg[i].c,
              "s": []
            });
          }
        }
        storageService.saveAutoCfg(this.data.did, autoCfg)
      }
      this.setData({
        autoCfg: JSON.parse(JSON.stringify(autoCfg)),
      });
      console.log(this.data.autoCfg);
      this.initChannels();

    },
    initChannels(timeObj) {
      let cls = this.data.autoCfg.modes[this.data.autoCfg.sel].cls;
      var channels = [];
      let nowObj = {};
      if (!comm.isEmptyObj(timeObj)) {
        nowObj = timeObj;
      } else {
        nowObj = this.getNowMinute();
      }
      for (var i = 0; i < cls.length; i++) {
        let newObj = {
          "n": cls[i].n,
          "nm": cls[i].nm,
          "c": cls[i].c
        };
        let vObj = this.getNowVal(nowObj.now, cls[i].s);
        newObj.ck = vObj.ck;
        newObj.v = vObj.v;
        channels.push(newObj);
      }
      this.setData({
        channels: channels,
        minutePickerVal: nowObj.nowStr
      });
      console.log(this.data.channels);
    },
    getNowMinute() {
      const currentTime = new Date();
      let hours = currentTime.getHours();
      let minutes = currentTime.getMinutes();
      if (minutes != 0 && minutes != 30) {
        if (minutes > 30) {
          minutes = 0;
          hours++;
          if (hours > 23) {
            hours--;
            minutes = 30;
          }
        } else {
          minutes = 30;
        }
      }
      let thours = hours < 10 ? ("0" + hours) : hours;
      let tminutes = minutes < 10 ? ("0" + minutes) : minutes;
      return {
        now: hours * 100 + minutes,
        nowStr: thours + ":" + tminutes
      };
    },
    getNowVal(now, sArr) {
      let ck = false;
      let v = 0;
      for (var i = 0; i < sArr.length; i++) {
        let tobj = sArr[i];
        if (tobj[0] == now) {
          ck = true;
          v = tobj[1];
          break;
        } else if (tobj[0] < now) {
          if (i == sArr.length - 1) { //最后一个
            //时间增大并且是最新一个时候默认带入前一个结果
            if (this.data.showChEdit && sArr.length > 0 && sArr[sArr.length - 1][1] > 0) {
              ck = true;
              v = sArr[sArr.length - 1][1];
            }
            break;
          } else {
            if (sArr[i + 1][0] <= now) {
              continue;
            } else {
              let v1 = tobj[1];
              let v2 = sArr[i + 1][1];
              let t1 = tobj[0];
              let t2 = sArr[i + 1][0];
              t1 = this.chgTime(t1);
              t2 = this.chgTime(t2);
              now = this.chgTime(now);
              if (v1 == v2) {
                v = v1;
              } else if (v1 < v2) {
                v = v1 + parseInt((v2 - v1) * (now - t1) / (t2 - t1));
              } else {
                v = v2 + parseInt((v1 - v2) * (t2 - now) / (t2 - t1));
              }
              break;
            }
          }
        }
      }
      return {
        ck: ck,
        v: v
      };
    },


    // 点击按钮后初始化图表
    init: function () {
      this.ecComponent.init((canvas, width, height, dpr) => {
        // 获取组件的 canvas、width、height 后的回调函数
        // 在这里初始化图表
        console.log(width + ":" + height + ":" + dpr)
        const chart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        chart.setOption(option);
        // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
        this.chart = chart;

        this.setData({
          isLoaded: true,
          isDisposed: false
        });

        // 注意这里一定要返回 chart 实例，否则会影响事件处理等
        return chart;
      });
    },
    dispose: function () {
      if (this.chart) {
        this.chart.dispose();
      }

      this.setData({
        isDisposed: true
      });
    },
    chgOption() {
      option.series[0].data[0] = 100;
      this.chart.setOption(option);
    },

    timePre() {
      let arr = this.data.minutePickerVal.split(":");
      let hour = parseInt(arr[0]);
      let minute = parseInt(arr[1]);
      if (minute == 0) {
        minute = 30;
        hour--;
        if (hour < 0) {
          return;
        }
      } else if (minute > 30) {
        minute = 30;
      } else {
        minute = 0;
      }
      let timeObj = {
        now: hour * 100 + minute
      };
      hour = hour < 10 ? ("0" + hour) : hour;
      minute = minute < 10 ? ("0" + minute) : minute;
      timeObj.nowStr = hour + ":" + minute;
      this.initChannels(timeObj);
    },
    timeNext() {
      let arr = this.data.minutePickerVal.split(":");
      let hour = parseInt(arr[0]);
      let minute = parseInt(arr[1]);
      if (minute < 30) {
        minute = 30;
      } else {
        minute = 0;
        hour++;
        if (hour > 23) {
          return;
        }
      }
      let timeObj = {
        now: hour * 100 + minute
      };
      hour = hour < 10 ? ("0" + hour) : hour;
      minute = minute < 10 ? ("0" + minute) : minute;
      timeObj.nowStr = hour + ":" + minute;
      this.initChannels(timeObj);
    },
    showPicker(e) {
      this.setData({
        minutePickerVisible: true
      });
    },
    hidePicker() {
      this.setData({
        minutePickerVisible: false
      });
    },
    pickerConfirm(e) {
      const {
        value
      } = e.detail;
      if (this.data.minutePickerVal == value) {
        return;
      }
      this.setData({
        minutePickerVisible: false
      });
      let arr = value.split(":");
      let hour = parseInt(arr[0]);
      let minute = parseInt(arr[1]);

      let timeObj = {
        now: hour * 100 + minute
      };
      hour = hour < 10 ? ("0" + hour) : hour;
      minute = minute < 10 ? ("0" + minute) : minute;
      timeObj.nowStr = hour + ":" + minute;
      this.initChannels(timeObj);
      this.hidePicker();
    },

    onColumnChange(e) {
      console.log('pick', e.detail.value);
    },

    sliderChange(e) {
      let idx = e.currentTarget.dataset.idx;
      let t = "channels[" + idx + "].val";
      this.setData({
        [t]: e.detail.value
      });
    },

    openDrawerBase() {
      this.setData({
        sidebarVisible: true
      });
    },
    exportCfg() {
      const $t = this;
      let data = Base64.encode(JSON.stringify(this.data.autoCfg));
      let tempPath = wx.env.USER_DATA_PATH + "/schedule.txt";
      try {
        wx.getFileSystemManager().writeFileSync(
          tempPath,
          data,
          'utf8'
        )
      } catch (e) {
        console.error(e);
        $t.showToast("生成文件异常!");
      }
      wx.shareFileMessage({
        filePath: tempPath,
      });
    },
    begImportCfg() {
      this.setData({
        popImportConfirmVisible: true
      });
    },
    importCfg() {
      const $t = this;
      wx.chooseMessageFile({
        count: 1,
        type: 'file',
        extension: ["txt"],
        success(res) {
          let file = res.tempFiles[0];
          wx.getFileSystemManager().readFile({
            filePath: file.path,
            encoding: 'utf-8',
            success(fileRes) {
              try {
                let data = Base64.decode(fileRes.data);
                let obj = JSON.parse(data);
                if (!(typeof obj === "object" && obj !== null)) {
                  throw "文件格式错误1";
                }
                if (obj["sel"] == null || obj["sel"] == undefined || obj["modes"] == null || obj["modes"] == undefined) {
                  throw "文件格式错误2";
                }
                if (obj.modes.length != $t.data.autoCfg.modes.length) {
                  throw "文件格式错误3";
                }
                $t.getAndInitChs(obj);
                $t.chgEchart();
                $t.showToast("导入成功!");
              } catch (e) {
                console.log(e);
                $t.showToast(e.message);
              }
            }
          })
        }
      })
    },
    closePopImportDialog() {
      this.setData({
        popImportConfirmVisible: false
      });
    },
    confirmPopImportDialog() {
      this.closePopImportDialog();
      this.importCfg();
    },





    selMode(e) {
      if (this.data.longtap) {
        this.data.longtap = false;
        return;
      }
      let idx = e.currentTarget.dataset.idx;
      if (this.data.autoCfg.sel == idx) {
        return;
      }
      this.setData({
        "autoCfg.sel": idx
      });
      storageService.saveAutoCfg(this.data.did, this.data.autoCfg)
      this.initChannels();
      this.chgEchart();
    },
    editModeName() {
      this.data.longtap = true;
      this.setData({
        showWithInput: true,
        modeName: this.data.autoCfg.modes[this.data.autoCfg.sel].nm
      });
    },
    editConfirm() {
      if (comm.isEmpty(this.data.modeName)) {
        this.showToast("名称不能为空!");
        this.setData({
          modeName: this.data.autoCfg.modes[this.data.autoCfg.sel].nm
        });
        return;
      }
      let str = "autoCfg.modes[" + this.data.autoCfg.sel + "].nm";
      this.setData({
        [str]: this.data.modeName
      });
      storageService.saveAutoCfg(this.data.did, this.data.autoCfg)
      this.closeDialog();
    },
    closeDialog() {
      this.setData({
        showWithInput: false
      });
    },
    bindKeyInput: function (e) {
      let val = e.detail.value;
      if (comm.isEmpty(val)) {
        val = "";
      }
      this.setData({
        modeName: val
      })
    },
    sliderChange(e) {
      this.valChange(e);
    },
    sliderChangeing(e) {
      this.valChange(e);
    },
    steppperChange(e) {
      this.valChange(e)
    },
    valChange(e) {
      let value = e.detail.value;
      let idx = e.currentTarget.dataset.idx;
      if (!this.data.showChEdit) {
        value = this.data.channels[idx].v;
      }
      let str = "channels[" + idx + "].v";
      this.setData({
        [str]: value
      });
    },
    sliderCkChange(e) {
      let idx = e.currentTarget.dataset.idx;
      let str = "channels[" + idx + "].ck";
      this.setData({
        [str]: e.detail.checked
      });
    },
    enableEdit() {
      this.setData({
        showChEdit: true
      });
    },
    cancelEdit() {
      this.setData({
        showChEdit: false
      });
      let arr = this.data.minutePickerVal.split(":");
      let hour = parseInt(arr[0]);
      let minute = parseInt(arr[1]);

      let timeObj = {
        now: hour * 100 + minute
      };
      hour = hour < 10 ? ("0" + hour) : hour;
      minute = minute < 10 ? ("0" + minute) : minute;
      timeObj.nowStr = hour + ":" + minute;
      this.initChannels(timeObj);
    },
    saveEdit() {
      let channles = this.data.channels;
      let flag = false;
      for (var i = 0; i < channles.length; i++) {
        if (!channles[i].ck) {
          continue;
        }
        this.saveAutoCfg(channles[i]);
        flag = true;
      }
      this.chgEchart();
      this.showToast(flag ? "保存成功!" : "没有设置需要保存!");
    },
    saveAutoCfg(chObj) {
      let cls = this.data.autoCfg.modes[this.data.autoCfg.sel].cls;
      let newArr = [];
      let arr = this.data.minutePickerVal.split(":");
      let time = parseInt(arr[0]) * 100 + parseInt(arr[1]);
      for (var i = 0; i < cls.length; i++) {
        if (cls[i].n == chObj.n) {
          let sArr = cls[i].s;
          let len = sArr.length;
          if (len == 0) {
            newArr.push([time, chObj.v]);
          } else {
            let isPush = false;
            for (var j = 0; j < len; j++) {
              if (sArr[j][0] == time) {
                newArr.push([time, chObj.v]);
                isPush = true;
              } else if (sArr[j][0] < time) {
                newArr.push(sArr[j]);
              } else {
                if (!isPush) {
                  newArr.push([time, chObj.v]);
                  isPush = true;
                }
                newArr.push(sArr[j]);
              }
            }
            if (!isPush) {
              newArr.push([time, chObj.v]);
            }
          }
          cls[i].s = newArr;
          storageService.saveAutoCfg(this.data.did, this.data.autoCfg)
          console.log(this.data.autoCfg);
          break;
        }
      }
    },
    showAllCfg() {
      let cls = this.data.autoCfg.modes[this.data.autoCfg.sel].cls;
      let times = [];
      let mapArr = [];
      for (var i = 0; i < cls.length; i++) {
        let tobj = {};
        for (var j = 0; j < cls[i].s.length; j++) {
          times.push(cls[i].s[j][0]);
          tobj["" + cls[i].s[j][0]] = cls[i].s[j][1];
        }
        mapArr.push(tobj);
      }
      let sorted = times.sort(function (a, b) {
        return a - b;
      });
      let uniques = sorted.filter((item, index, self) => {
        return self.indexOf(item) === index;
      });
      let popTimes = [];
      for (var j = 0; j < uniques.length; j++) {
        let str = [];
        for (var i = 0; i < mapArr.length; i++) {
          let t = mapArr[i]["" + uniques[j]];
          str.push(t == null ? "-" : t);
        }
        let m = uniques[j] % 100;
        let h = parseInt(uniques[j] / 100);
        h = h < 10 ? ("0" + h) : h;
        m = m < 10 ? ("0" + m) : m;
        popTimes.push({
          t: h + ":" + m,
          l: str.join(",")
        });
      }
      this.setData({
        popVisible: true,
        popTimes: popTimes
      });
    },
    popClose() {
      this.setData({
        popVisible: false
      });
    },
    popDelTime(e) {
      let time = e.currentTarget.dataset.t;
      this.data.popDelTime = time;
      this.setData({
        popDelConfirmVisible: true
      });
    },
    popEditTime(e) {
      let time = e.currentTarget.dataset.t;
      let lstr = e.currentTarget.dataset.l;
      let arr = lstr.split(",");
      for (var i = 0; i < this.data.channels.length; i++) {
        let v = arr[i];
        this.data.channels[i].ck = (v != "-");
        this.data.channels[i].v = (v == "-" ? 0 : v);
      }
      this.setData({
        channels: this.data.channels,
        minutePickerVal: time,
        showChEdit: true,
        popVisible: false
      });
    },
    closePopDelDialog() {
      this.setData({
        popDelConfirmVisible: false
      });
    },
    confirmPopDelDialog() {
      this.closePopDelDialog();
      let arr = [];
      for (var i = 0; i < this.data.popTimes.length; i++) {
        if (this.data.popTimes[i].t != this.data.popDelTime) {
          arr.push(this.data.popTimes[i]);
        }
      }
      let cls = this.data.autoCfg.modes[this.data.autoCfg.sel].cls;
      let tArr = this.data.popDelTime.split(":");
      let time = parseInt(tArr[0]) * 100 + parseInt(tArr[1]);
      for (var i = 0; i < cls.length; i++) {
        let tsArr = [];
        for (var j = 0; j < cls[i].s.length; j++) {
          if (time != cls[i].s[j][0]) {
            tsArr.push(cls[i].s[j]);
          }
        }
        if (tsArr.length != cls[i].s.length) {
          cls[i].s = tsArr;
        }
      }
      storageService.saveAutoCfg(this.data.did, this.data.autoCfg)
      this.setData({
        popTimes: arr
      });
      this.chgEchart();
    },
    chgTime(time) {
      let m = time % 100;
      return parseInt(time / 100) * 100 + parseInt(m * 100 / 60);
    },
    chgTimeArr(tArr) {
      let arr = [];
      for (var i = 0; i < tArr.length; i++) {
        arr.push([this.chgTime(tArr[i][0]), tArr[i][1]]);
      }
      return arr;
    },
    initEchartOption() {
      console.log(this.data.autoCfg);
      let cls = this.data.autoCfg.modes[this.data.autoCfg.sel].cls;
      let legendArr = [];
      let seriesArr = [];
      let min = 2400;
      let max = 0;
      for (var i = 0; i < cls.length; i++) {
        legendArr.push({
          name: cls[i].nm,
          textStyle: {
            color: cls[i].c,
            fontSize: 10
          }
        });
        let sArr = this.chgTimeArr(cls[i].s);
        seriesArr.push({
          name: cls[i].nm,
          type: 'line',
          smooth: false,
          lineStyle: {
            color: cls[i].c, // 折线颜色
            width: 2
          },
          itemStyle: {
            color: cls[i].c, // 折线颜色
          },
          data: sArr
        });
        if (sArr.length > 0) {
          if (sArr[0][0] < min) {
            min = sArr[0][0];
          }
          if (sArr[sArr.length - 1][0] > max) {
            max = sArr[sArr.length - 1][0];
          }
        }
      }
      if (min == 2400) {
        min = 0;
      } else {
        if (min > 100) {
          min = parseInt((min - 100) / 100) * 100;
        } else {
          min = 0;
        }
      }
      if (max == 0) {
        max = 2300;
      } else {
        if (max < 2300) {
          max = parseInt((max + 100) / 100) * 100;
        } else {
          max = 2300;
        }
      }
      if (max - min < 800) {
        let diff = parseInt((8 - (max - min) / 100) / 2);
        if (min / 100 - diff < 0) {
          min = 0;
          max = 800;
        } else if (max / 100 + diff > 23) {
          max = 2300 + max % 100;
          min = parseInt(max / 100) * 100 - 800;
        } else {
          min = min - diff * 100;
          max = max + diff * 100;
        }
      }

      option.legend.data = legendArr;
      option.series = seriesArr;
      option.xAxis.min = min;
      option.xAxis.max = max;
      //console.log(option);
      //console.log(JSON.stringify(option));
    },
    chgEchart() {
      this.initEchartOption();
      this.chart.setOption(option);
    },
    closePopSyncToDeviceDialog() {
      this.setData({
        popSyncToDeviceConfirmVisible: false
      });
    },
    confirmPopSyncToDeviceDialog() {
      this.closePopSyncToDeviceDialog();
      const $t = this;
      wx.showLoading({
        title: 'Loading......',
        mask: true,
        success: function () {
          let chCfg = storageService.getDeviceChannels($t.data.did)
          let cls = $t.data.autoCfg.modes[$t.data.autoCfg.sel].cls;
          let tl = [];
          for (var i = 0; i < chCfg.length; i++) {
            if (chCfg[i].u == 0) {
              tl.push([]);
              continue;
            }
            let exists = false;
            for (var j = 0; j < cls.length; j++) {
              if (chCfg[i].n == cls[j].n) {
                exists = true;
                var arr = JSON.parse(JSON.stringify(cls[j].s));
                for (var n = 0; n < arr.length; n++) {
                  arr[n][0] = arr[n][0] * 100;
                }
                tl.push(arr);
                break;
              }
            }
            if (!exists) {
              tl.push([]);
            }
          }
          appInstance.sendMtMsg($t.data.deviceCfg.topicSend, "syncDataUp", {
            "t": 1,
            "s": $t.data.autoCfg.sel,
            "n": $t.data.autoCfg.modes[$t.data.autoCfg.sel].nm,
            "tl": tl
          });
          $t.data.timeoutObj = setTimeout(function () {
            $t.confirmPopSyncToDeviceDialogResult(0);
          }, 5000);
        }
      });
    },
    confirmPopSyncToDeviceDialogResult(succ) {
      const $t = this;
      wx.hideLoading();
      if (succ == 0) {
        $t.showToast("请求响应超时...");
      } else {
        $t.showToast("同步成功!");
        this.triggerEvent('setTitle', {
          type: 1,
          title: $t.data.autoCfg.modes[$t.data.autoCfg.sel].nm
        });
        clearTimeout($t.data.timeoutObj);
      }
    },
    closePopSyncFromDeviceDialog() {
      this.setData({
        popSyncFromDeviceConfirmVisible: false
      });
    },
    confirmPopSyncFromDeviceDialog() {
      this.closePopSyncFromDeviceDialog();
      const $t = this;
      wx.showLoading({
        title: 'Loading......',
        mask: true,
        success: function () {
          appInstance.sendMtMsg($t.data.deviceCfg.topicSend, "syncDataDown", null);
          $t.data.timeoutObj = setTimeout(function () {
            $t.confirmPopSyncFromDeviceDialogResult(0);
          }, 5000);
        }
      });
    },
    confirmPopSyncFromDeviceDialogResult(succ, dcfg) {
      const $t = this;
      wx.hideLoading();
      if (succ == 0) {
        $t.showToast("请求响应超时...");
      } else {
        if (dcfg.t !== undefined && dcfg.t != 1) {
          $t.showToast("设备运行模式非当前模式，未有相关数据!");
          return;
        }
        $t.showToast("同步成功!");
        clearTimeout($t.data.timeoutObj);
        console.log(dcfg);
        $t.data.autoCfg.sel = dcfg.s;
        console.log($t.data.autoCfg);
        $t.data.autoCfg.modes[dcfg.s].nm = dcfg.n;
        let chCfg = storageService.getDeviceChannels(this.data.did)
        let cls = [];
        for (var i = 0; i < chCfg.length; i++) {
          if (chCfg[i].u == 0) {
            continue;
          }
          var arr = dcfg.tl.length > i ? dcfg.tl[i] : [];
          if (arr.length > 0 && dcfg.t !== undefined) {
            for (var n = 0; n < arr.length; n++) {
              arr[n][0] = parseInt(arr[n][0] / 100);
            }
          }
          cls.push({
            "n": chCfg[i].n,
            "nm": chCfg[i].nm,
            "c": chCfg[i].c,
            "s": arr
          });
        }
        $t.data.autoCfg.modes[dcfg.s].cls = cls;
        storageService.saveAutoCfg(this.data.did, $t.data.autoCfg)
        $t.setData({
          autoCfg: $t.data.autoCfg
        });
        $t.initChannels();
        this.chgEchart();
      }
    },
    cfgLeft() {
      let cls = this.data.autoCfg.modes[this.data.autoCfg.sel].cls;
      for (var i = 0; i < cls.length; i++) {
        let tl = cls[i].s;
        for (var j = 0; j < tl.length; j++) {
          let time = tl[j][0];
          let h = parseInt(time / 100);
          let m = time % 100;
          if (m >= 30) {
            m -= 30;
          } else {
            if (h > 0) {
              m = m + 30;
              h -= 1;
            }
          }
          tl[j][0] = h * 100 + m;
        }
      }
      storageService.saveAutoCfg(this.data.did, this.data.autoCfg)
      this.chgEchart();
      this.initChannels();
    },
    cfgRight() {
      let cls = this.data.autoCfg.modes[this.data.autoCfg.sel].cls;
      for (var i = 0; i < cls.length; i++) {
        let tl = cls[i].s;
        for (var j = 0; j < tl.length; j++) {
          let time = tl[j][0];
          let h = parseInt(time / 100);
          let m = time % 100;
          if (m >= 30) {
            if (h < 23) {
              h += 1;
              m -= 30;
            }
          } else {
            m += 30;
          }
          tl[j][0] = h * 100 + m;
        }
      }
      storageService.saveAutoCfg(this.data.did, this.data.autoCfg)
      this.chgEchart();
      this.initChannels();
    },
    cfgReduce() {
      let cls = this.data.autoCfg.modes[this.data.autoCfg.sel].cls;
      for (var i = 0; i < cls.length; i++) {
        let tl = cls[i].s;
        for (var j = 0; j < tl.length; j++) {
          let v = tl[j][1];
          if (v == 0) {
            continue;
          }
          v -= 5;
          if (v < 0) {
            v = 0;
          }
          tl[j][1] = v;
        }
      }
      storageService.saveAutoCfg(this.data.did, this.data.autoCfg)
      this.chgEchart();
      this.initChannels();
    },
    cfgEnlarge() {
      let cls = this.data.autoCfg.modes[this.data.autoCfg.sel].cls;
      for (var i = 0; i < cls.length; i++) {
        let tl = cls[i].s;
        for (var j = 0; j < tl.length; j++) {
          let v = tl[j][1];
          if (v == 0) {
            continue;
          }
          v += 5;
          if (v > 100) {
            v = 100;
          }
          tl[j][1] = v;
        }
      }
      storageService.saveAutoCfg(this.data.did, this.data.autoCfg)
      this.chgEchart();
      this.initChannels();
    },
    syncToDevice() {
      let cls = this.data.autoCfg.modes[this.data.autoCfg.sel].cls;
      let flag = 0;
      for (var i = 0; i < cls.length; i++) {
        if (cls[i].s.length > 0) {
          flag = 1;
          break;
        }
      }
      if (flag == 0) {
        this.showToast("没有数据需要同步!");
        return;
      }
      this.setData({
        popSyncToDeviceConfirmVisible: true
      });
    },
    syncFromDevice() {
      let autoRunCfg = storageService.getAutoRunCfg(this.data.did)
      let syncType = autoRunCfg.syncType == null ? 0 : autoRunCfg.syncType;
      if (syncType != "1") {
        this.showToast("没有数据需要同步!");
        return;
      }
      this.setData({
        popSyncFromDeviceConfirmVisible: true
      });
    },






    showToast(msg) {
      // 子组件中
      this.triggerEvent('showToast', {
        msg: msg
      });
    },
  },
})